package com.hcf.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hcf.admin.common.biz.user.UserContext;
import com.hcf.admin.common.convention.result.Result;
import com.hcf.admin.dao.entity.GroupDO;
import com.hcf.admin.dao.mapper.GroupMapper;
import com.hcf.admin.dto.req.ShortLinkGroupSortReqDto;
import com.hcf.admin.dto.req.ShortLinkGroupUpateReqDto;
import com.hcf.admin.dto.req.ShortlinkGroupSaveReqDto;
import com.hcf.admin.dto.resp.GroupRespDto;
import com.hcf.admin.remote.ShortLinkProjectService;
import com.hcf.admin.remote.dto.resp.ListShortLinkCountRespDTO;
import com.hcf.admin.service.GroupService;
import com.hcf.admin.util.RandomCodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
@Slf4j
public class GroupServiceImpl extends ServiceImpl<GroupMapper, GroupDO> implements GroupService {
    @Override
    public void saveGroup(ShortlinkGroupSaveReqDto shortlinkGroupSaveReqDto) {
        saveGroup(UserContext.getUsername(), shortlinkGroupSaveReqDto);
    }

    @Override
    public void saveGroup(String username, ShortlinkGroupSaveReqDto shortlinkGroupSaveReqDto) {
        // 保证gid去重
        String gid;
        do {
            gid = RandomCodeUtil.generateRandomGID();
        } while (hasGid(username, gid));

        GroupDO groupDO = new GroupDO();
        groupDO.setGid(gid)
                .setName(shortlinkGroupSaveReqDto.getName())
                .setUsername(username);
        baseMapper.insert(groupDO);
        return;
    }

    @Override
    public List<GroupRespDto> listGroup() {
        LambdaQueryWrapper<GroupDO> wrapper = Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getDelFlag, 0)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .orderByDesc(GroupDO::getSortOrder, GroupDO::getUpdateTime);
        List<GroupDO> groupDOList = baseMapper.selectList(wrapper);
        //远程查询短链数量
        ShortLinkProjectService shortLinkProjectService = new ShortLinkProjectService() {
        };
        Result<List<ListShortLinkCountRespDTO>> listResult = shortLinkProjectService.listShortLinkCount(
                groupDOList.stream().map(GroupDO::getGid).collect(Collectors.toList()));

        List<GroupRespDto> groupRespDtoList = BeanUtil.copyToList(groupDOList, GroupRespDto.class);
        groupRespDtoList.forEach(item ->{
            Optional<ListShortLinkCountRespDTO> optional = listResult.getData().stream()
                    .filter(item1 -> item1.getGid().equals(item.getGid()))
                    .findFirst();
            if(optional.isPresent()){
                    item.setLinkCount(optional.get().getCount());
            }
        });

        return groupRespDtoList;
    }

    @Override
    public boolean updateGroup(ShortLinkGroupUpateReqDto groupUpateReqDto) {
        LambdaQueryWrapper<GroupDO> eq = Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getGid, groupUpateReqDto.getGid())
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .eq(GroupDO::getDelFlag, 0);
        baseMapper.update(BeanUtil.toBean(groupUpateReqDto, GroupDO.class), eq);
        return true;
    }

    @Override
    public boolean deleteGroup(String id) {
        LambdaQueryWrapper<GroupDO> eq = Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getGid, id)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .eq(GroupDO::getDelFlag, 0);
        GroupDO groupDO = new GroupDO();
        groupDO.setDelFlag(1);
        baseMapper.update(groupDO, eq);
        return true;
    }

    @Override
    public void sortGroup(ShortLinkGroupSortReqDto groupSortReqDto) {
        LambdaQueryWrapper<GroupDO> eq = Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getGid, groupSortReqDto.getGid())
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .eq(GroupDO::getDelFlag, 0);
        GroupDO groupDO = new GroupDO();
        groupDO.setSortOrder(groupSortReqDto.getSortOrder());
        baseMapper.update(groupDO, eq);
    }

    private Boolean hasGid(String username, String gid){
        QueryWrapper<GroupDO> queryWrapper = new QueryWrapper<GroupDO>();
        queryWrapper.eq("gid", gid)
                .eq("username", username);
        Object o = baseMapper.selectOne(queryWrapper);
        return o!= null;
    }

}
